package com.wptai.disconf.client.core;

import com.wptai.disconf.client.data.DisconfData;
import com.wptai.disconf.client.utils.YamlUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 前置处理，包括：
 * 1：解析并且获取参数
 * 2：生成disconf.property配置文件
 */
@Data
@Slf4j
public class DisConfigPreProcessing {

    private Map<String,Object> hashParamMap = new HashMap<>();

    private DisconfData disconfData = new DisconfData();

    public DisConfigPreProcessing() {
    }

    public void init() {
        //解析参数
        disconfData.paramList.forEach(p -> {
            Object value;
            //支持从环境变量里面获取值
            if(System.getProperty(p) != null){
                value = System.getProperty(p);
            }else{
                value = YamlUtil.getValue(DisconfData.APPLICATION_FILE_NAME, p);
            }
            String key = p.replaceAll("\\.","_");
            hashParamMap.put(key,value);
        });
        disconfData.setScan(hashParamMap.get(DisconfData.DISCONF_CONFIG_BASE_SCAN.replaceAll("\\.","_")).toString());
        disconfData.setAutoReloadFiles(hashParamMap.get(DisconfData.DISCONF_CONFIG_AOTO_RELOAD_FILES.replaceAll("\\.","_")).toString());

        try{
            generateDisProFile();
        }catch (Exception ex){
            log.error("saveDisProFile is error", ex);
        }
    }

    public void generateDisProFile() throws Exception{

        /**
         * 构建disconf配置文件模板
         */
        // 初始化并取得Velocity引擎
        VelocityEngine ve = new VelocityEngine();
        ve.init();
        // 取得velocity的模版内容, 模板内容来自字符传
        String veContent = DisconfData.getContentDisconfPropertiesVM();
        //构造参数
        VelocityContext context = new VelocityContext(hashParamMap);
        //渲染模板
        StringWriter sw = new StringWriter();
        //动态构建
        ve.evaluate(context,sw, "", veContent);

        /**
         * 生成 disconf 配置文件
         */
        String disProFilePath = this.getClass().getResource("/").getPath()+DisconfData.DISCONF_FILE_NAME;
        File disProFile = new File(disProFilePath);
        //删除历史
        if(disProFile.exists()){
            disProFile.delete();
        }
        //生成disconf
        disProFile.createNewFile();
        FileWriter resultFile = new FileWriter(disProFile);
        resultFile.write(sw.toString());
        //清空、关闭
        resultFile.flush();
        resultFile.close();
    }

    public void destroy() {
        disconfData = null;
        hashParamMap.clear();
    }


}
